package com.hc.tenant.listener;

import com.alibaba.fastjson.JSON;
import com.hc.common.core.utils.StringUtils;

import com.hc.tenant.domain.Location;
import com.hc.tenant.listener.event.LocationEvent;
import com.hc.tenant.listener.event.MqttEvent;
import com.hc.tenant.service.ILocationService;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LocationListener implements  MqttEventListener {

    @Autowired
    private ILocationService locationService;

    @Override
    public void onMqttEvent(MqttEvent mqttEvent) {
        if(StringUtils.equals(LocationEvent.EVENT_NAME, (String)mqttEvent.getSource())){
            MqttMessage message = mqttEvent.getMqttMessage();
            Location location = JSON.parseObject(message.getPayload(), Location.class);
            if(location!= null){
                if(location.getLocationId()!=null && location.getLocationId()>0){
                    locationService.updateLocation(location);
                }else {
                    locationService.insertLocation(location);
                }
            }
        }
    }
}
